package com.haidong;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * cookie是客户端的会话技术
 * 会话中的cookie和session都是以客户端浏览器为单位的,如果不设置生存期,在浏览器关闭后就会失效
 */
@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在servlet对象中创建cookie对象,并发送cookie,cookie无法存储中文,通过编码存储
        String value = "这是个中文名";
        value = URLEncoder.encode(value,"utf-8");
        System.out.println("存储的数据实际是" + value);
        Cookie cookie = new Cookie("username",value);
        // 设置cookie存活时间,设置为负数则为默认值关闭浏览器就清除,0表示立即清除
        cookie.setMaxAge(60*60*24*7);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
